<?php

namespace app\admin\controller\activityform;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use fast\Tree;

/**
 * 表单url题库
 *
 * @icon fa fa-circle-o
 */
class Fromurlque extends Backend
{

    /**
     * Fromurlque模型对象
     * @var \app\admin\model\Fromurlque
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\activityform\Fromurlque;
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('type', 'neq', "text")
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('type', 'neq', "text")
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    //验证关联
                    if ($params['ifrelated'] == 'yes') {
                        if (empty($params['cp_trans_id']) || empty($params['cp_trans_ids'])) {
                            $this->error('如需关联则父级两项为必填!');
                        } else {
                            $params['pid'] = $params['cp_trans_ids'];
                        }
                    } else {
                        $params['pid'] = 0;
                    }


                    //在这里增加
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        if (($params['type'] == 'radio') || ($params['type'] == 'checkbox')) {
                            //name tyep pid
                            $tmp = [];
                            foreach ($params['type_desc'] as $v) {
                                $tmptmp['pid'] = $this->model->getLastInsID();
                                $tmptmp['name'] = $v;
                                $tmptmp['type'] = 'text';
                                $tmp[] = $tmptmp;

                                unset($tmptmp);
                            }

                            $this->model->allowField(true)->insertAll($tmp);
                        }
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function parentOption()
    {
        $data = $this->model->where("type in ('radio')")->select();

        return json(['list' => $data, 'total' => count($data)]);
    }

    public function parentOptions()
    {
        $data = $this->model->where("type in ('radio','checkbox','input')")->select();
        $dataAll = $this->model->select();

        $dataAlls = [];
        foreach ($dataAll as $v) {
            $dataAlls[$v['id']] = $v;
        }


        foreach ($dataAlls as &$v) {
            if (!empty($v['pid']) && ($v['type'] != 'text') && !empty($dataAlls[$dataAlls[$v['pid']]['pid']])) {
                if (strpos($dataAlls[$dataAlls[$v['pid']]['pid']]['name'], '(有关联)') !== false) {
                } else {
                    $dataAlls[$dataAlls[$v['pid']]['pid']]['name'] .= '(有关联)';
                }
            }
        }
        unset($v);

        foreach ($dataAlls as $key => $v) {
            if ($v['type'] == 'text') {
                unset($dataAlls[$key]);
            }
        }
        $dataAlls = array_merge($dataAlls);
        return json(['list' => $dataAlls, 'total' => count($dataAlls)]);
    }

    public function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);
        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        if ($primaryvalue == "" || $primaryvalue == null) {
            $order = "field(`{$primarykey}`, 0)";
        } else {
            $order = "field(`{$primarykey}`, {$primaryvalue})";
        }

        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $datalist = $this->model->where($where)
                ->orderRaw($order)
                ->page($page, $pagesize)
                ->field($this->selectpageFields)
                ->select();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field => isset($item[$field]) ? $item[$field] : '',
                    'pid' => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
            if ($istree) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            {
                //查找被删除的题目是否已在表单中应用
                $from = new \app\admin\model\activityform\Fromurl;

                foreach (explode(',', $ids) as $idsv) {
                    $fromFind = $from->whereRaw('find_in_set(:idsv,fromurlques_ids)',['idsv'=>$idsv])
                        ->field('GROUP_CONCAT(id) as fromids')
                        ->find();
                    if ($fromFind->fromids) {
                        $this->error("题目{$idsv}已在表单{$fromFind->fromids}中使用,如确需删除需先删除表单{$fromFind->fromids}");
                    }
                }

            }
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
